package com.fivefox.event.util;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Base64;

/**
 * @author: 李任起
 * @description: 类描述
 * @createDate: 2024-02-27 14:41
 */
public class AESUtil {
    private static final String AES = "AES";
    private static final String SHA_256 = "SHA-256";
    private static final String AES_CBC_NO_PADDING = "AES/CBC/NOPADDING";

    public static String decrypt(String encryptKey, String encrypt) throws Exception {
        // 偏移向量
        byte[] iv = new byte[16];
        // 密文解码
        byte[] decode = Base64.getDecoder().decode(encrypt);
        // 字节处理
        System.arraycopy(decode, 0, iv, 0, 16);
        byte[] data = new byte[decode.length - 16];
        System.arraycopy(decode, 16, data, 0, data.length);
        // 明文
        byte[] bytes;
        try {
            // 密钥解码
            byte[] key = MessageDigest.getInstance(SHA_256).digest(encryptKey.getBytes(StandardCharsets.UTF_8));
            // 定义解密方式
            Cipher cipher = Cipher.getInstance(AES_CBC_NO_PADDING);
            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, AES), new IvParameterSpec(iv));
            // 解密
            bytes = cipher.doFinal(data);
        } catch (Exception e) {
            throw new Exception("事件消息解密失败", e);
        }
        if (bytes.length > 0) {
            int p = bytes.length - 1;
            while (p >= 0 && bytes[p] <= 16) {
                p--;
            }
            if (p != bytes.length - 1) {
                byte[] rr = new byte[p + 1];
                System.arraycopy(bytes, 0, rr, 0, p + 1);
                bytes = rr;
            }
        }
        return new String(bytes, StandardCharsets.UTF_8);
    }
}
